//
//  ActionViewController.m
//  FengWoFilterTickerDemo
//
//  Created by YingShi on 15/10/26.
//  Copyright © 2015年 FengWo. All rights reserved.
//

#import "ActionViewController.h"
#import "ZDStickerView.h"
#import "FiltersView.h"
#import "UIImage+Filters.h"
#import "FilterImage.h"
#import "FWEditGoodsTagView.h"
#import "FWGoodsTagView.h"
#import "ShowFilterBtn.h"
#import "FWEditGoodsTagView.h"
#import <objc/message.h>

typedef enum {
    DidChoiceAddLabel = 0,
    DidChoiceAddImage = 1,
    DidChoicdAddFilterImage = 2,

}EditingButtonSelected;


#define imageOriSizeWidth 113

@interface ActionViewController ()<ZDStickerViewDelegate, FWEditGoodsTagViewDelegate, FWGoodsTagViewDelegate>
{
    IBOutlet UIScrollView *scrollEffect;
    IBOutlet UIImageView *imgToDo;
    UIImage * _tempChoiceImage;
    UIImage * _saveImage; //合成后的图片
    EditingButtonSelected userChoiceBtn;
    ShowFilterBtn *selectFilterBtn;
}
@property (strong, nonatomic) IBOutlet UILabel *addLabelInfo;
@property (strong, nonatomic) IBOutlet UIButton *addImageViewButton;
@property (strong, nonatomic, nullable)NSMutableArray * picMutableArray;
@property (strong, nonatomic, nullable)ZDStickerView *userResizableView1;
@property (nonatomic, strong) UIView *tagLayerView;                 // 标签层  用于显示并操作标签
@property (nonatomic, strong) FWEditGoodsTagView *editGoodsTagView; // 编辑标签视图  用于添加或修改标签
@property (nonatomic, strong) FWGoodsTagView *goodsTagView;         // 商品标签
@property (nonatomic, assign) CGPoint goodsTagPoint;                // 商品标签的中心位置

@property (nonatomic, strong) FiltersView *filtersView;

@end


@implementation ActionViewController

- (void)loadView {
    [super loadView];
    
    [self buildTagLayerView];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _picMutableArray = [NSMutableArray arrayWithObjects:[UIImage imageNamed:@"saoDang1"],[UIImage imageNamed:@"saoDang2"],[UIImage imageNamed:@"saoDang3"],[UIImage imageNamed:@"saoDang4"], nil];
    scrollEffect.showsHorizontalScrollIndicator = NO;
    scrollEffect.backgroundColor = [UIColor lightGrayColor];
    scrollEffect.bounces = NO;
    _tempChoiceImage = [[UIImage alloc]init];
    [self createSubviews];
    
    scrollEffect.hidden = YES;
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    
    self.tagLayerView.frame = CGRectMake(0, 0, imgToDo.bounds.size.width, imgToDo.bounds.size.height);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)dealloc
{
    self.picMutableArray = nil;
    self.userResizableView1 = nil;
}

#pragma mark - Private
- (void)createSubviews
{
    if (_imgInput) {
        [imgToDo setImage:_imgInput];
    }
}

#pragma mark - Builder View
- (void)buildTagLayerView {
    self.tagLayerView = [[UIView alloc] init];
    self.tagLayerView.backgroundColor = [UIColor clearColor];
    self.tagLayerView.clipsToBounds = YES;
    [imgToDo addSubview:self.tagLayerView];
    // 添加tap手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapOnTagLayerView:)];
    [self.tagLayerView addGestureRecognizer:tap];
}

#pragma mark - Selector Method
- (void)tapOnTagLayerView:(UITapGestureRecognizer *)tap {
    self.goodsTagPoint = [tap locationInView:tap.view];
    
    if (_editGoodsTagView) {
        [_editGoodsTagView removeFromSuperview];
        _editGoodsTagView = nil;
    }
    _editGoodsTagView = [[FWEditGoodsTagView alloc] initWithFrame:self.view.bounds];
    _editGoodsTagView.delegate = self;
    _editGoodsTagView.type = FWEditGoodsTagViewTypeAdd;
    [self.view addSubview:_editGoodsTagView];
}

#pragma mark - ZDStickerViewDelegate
- (void)stickerViewDidClose:(ZDStickerView *)sticker {

    self.userResizableView1 = nil;
}



#pragma mark - ButtonMethord
// 关闭此屏幕
- (IBAction)btnCloseClicked:(id)sender
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
    
}

#pragma mark - SaveButtonMethord -
//保存“确定”button
- (IBAction)didTappedAddmitButton:(UIButton *)sender {
    
    NSLog(@"tapped addmit button");
    if (userChoiceBtn == DidChoiceAddImage) {
    
        UIImageView *close = objc_msgSend(_userResizableView1, NSSelectorFromString(@"deleteControl"));
        close.hidden = YES;
        
        UIImageView *resize = objc_msgSend(_userResizableView1, NSSelectorFromString(@"resizingControl"));
        resize.hidden = YES;
        
        _tagLayerView.hidden = YES;
        /*
         初始化context
         */
        UIGraphicsBeginImageContextWithOptions(imgToDo.bounds.size, NO, 0.0); //准备画布尺寸
        CGContextRef context = UIGraphicsGetCurrentContext();//准备画布

        [imgToDo.layer renderInContext:context];
        _saveImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        UIImageWriteToSavedPhotosAlbum(_saveImage, self, nil, nil);

        
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"保存成功" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alert show];
        
        close.hidden = NO;
        resize.hidden = NO;
        _tagLayerView.hidden = NO;

    }
}

#pragma mark - GestureMethord
//双击图案编辑
- (void)didTappedTwiceImage:(UITapGestureRecognizer *)tapGes {
    NSLog(@" u tapped twice image");
}

//单击scrollView 上的图选择
- (void)didUserTappedImage:(UITapGestureRecognizer *)tap {
    
    NSInteger tapedViewTag = tap.view.tag - 100;
    UIImageView *imageView = [[UIImageView alloc]
                              initWithImage:[self.picMutableArray objectAtIndex:tapedViewTag]];
    _tempChoiceImage = [self.picMutableArray objectAtIndex:tapedViewTag];
    
    imageView.userInteractionEnabled = YES;
    UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(didTappedTwiceImage:)];
    tapGesture.numberOfTapsRequired = 2;
    [imageView addGestureRecognizer:tapGesture];
    if (!self.userResizableView1) {
        CGRect gripFrame1 = CGRectMake((imgToDo.frame.size.width - 113)/2,(imgToDo.frame.size.height - 113)/2, 113, 113);
        self.userResizableView1 = [[ZDStickerView alloc] initWithFrame:gripFrame1];
        self.userResizableView1.delegate = self;
    }
    _userResizableView1.contentView = imageView;
    _userResizableView1.preventsPositionOutsideSuperview = NO;
    [_userResizableView1 showEditingHandles];
    [imgToDo addSubview:_userResizableView1];
}

#pragma mark -
#pragma mark 添加特效(标签 贴纸 滤镜)
// 添加标签
- (IBAction)btnAddTagClicked:(id)sender
{
    // TODO
    userChoiceBtn = DidChoiceAddLabel;
    self.tagLayerView.userInteractionEnabled = YES;
    
    _addLabelInfo.hidden = NO;
    scrollEffect.hidden = YES;
}


//选择某个滤镜特效
- (void)chooseFilterImageClicked:(ShowFilterBtn *)selectFilterImage
{
    //改变选中框的状态
    selectFilterBtn.imageView.layer.borderWidth = 0;
    selectFilterBtn = selectFilterImage;
    selectFilterBtn.imageView.layer.borderColor = [UIColor grayColor].CGColor;
    selectFilterBtn.imageView.layer.borderWidth = 2;
    
    __weak typeof(self) weakself = self;
    
    if (selectFilterBtn.tag/1000 - 1 == 0 ) {
        [imgToDo setImage:self.imgInput] ;
        return;
    }
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        FilterImage *filerImage = [[FilterImage alloc] init];
        UIImage *image = [filerImage selectFilterImageWithTag:selectFilterBtn.tag/1000 - 1 inputImage:weakself.imgInput];
        dispatch_async(dispatch_get_main_queue(), ^{
            [imgToDo setImage:image];
        });
    });
   
}


// 添加滤镜
- (IBAction)btnAddFilterClicked:(id)sender
{
    self.tagLayerView.userInteractionEnabled = NO;
    _addLabelInfo.hidden = YES;
    scrollEffect.hidden = NO;
    for (UIView *imageView in scrollEffect.subviews) {
        if ([imageView isKindOfClass:[UIImageView class]]) {
            [imageView removeFromSuperview];
        }
    }
    
    NSArray *nameArr = @[@"原始",@"暧昧",@"淡蓝",@"淡黄",@"复古",@"高冷",@"怀旧",@"胶片",@"可爱",@"落寞",@"加强",@"暖心",@"清新",@"日系",@"温暖"];
    scrollEffect.contentSize = CGSizeMake(100*15+5, scrollEffect.frame.size.height);
    for (int i=0; i<15; i++) {
        ShowFilterBtn *btn = [[ShowFilterBtn alloc] initWithFrame:CGRectMake(5+100*i, 0,95, scrollEffect.frame.size.height)];
        
        [scrollEffect addSubview:btn];
        btn.tag = (i+1)*1000;
        [btn setTitle:nameArr[i] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
        [btn setImage:self.imgInput forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(chooseFilterImageClicked:) forControlEvents:UIControlEventTouchUpInside];
        if (i==0) {
            selectFilterBtn = btn;
        }
    }
    
    selectFilterBtn.imageView.layer.borderColor = [UIColor grayColor].CGColor;
    selectFilterBtn.imageView.layer.borderWidth = 2;

    __weak typeof(self) weakself = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        FilterImage *filerImage = [[FilterImage alloc] init];
        NSArray *imgArr =  [filerImage getFilterImagesFromInputImage:weakself.imgInput];
        dispatch_async(dispatch_get_main_queue(), ^{
            for (int i=0; i<imgArr.count; i++) {
                ShowFilterBtn *btn = [scrollEffect viewWithTag:(i+1)*1000];
                [btn setImage:imgArr[i] forState:UIControlStateNormal];
                btn.imageView.contentMode = UIViewContentModeScaleToFill;
            }
        });
    });
}

//贴纸
- (IBAction)didTappedAddImageButton:(UIButton *)sender {
    
    self.tagLayerView.userInteractionEnabled = NO;
    _addLabelInfo.hidden = YES;
    scrollEffect.hidden = NO;
    
    for (UIView *imageView in scrollEffect.subviews) {
        if ([imageView isKindOfClass:[ShowFilterBtn class]]) {
            [imageView removeFromSuperview];
        }
    }
    
    userChoiceBtn = DidChoiceAddImage;
    CGFloat imageWidth = imageOriSizeWidth;
    CGFloat imageHeight = imageWidth;

    
    scrollEffect.contentSize = CGSizeMake(imageWidth * _picMutableArray.count, imageHeight);
    
    if (self.picMutableArray.count == 0 ) {
        return;
    }
    
    for (int i = 0 ; i < self.picMutableArray.count ; i ++) {
        
        UIImageView * imageView = [[UIImageView alloc]initWithFrame:CGRectMake(i*(imageWidth+4), 0, imageWidth, imageHeight)];
        imageView.tag = 100+i;
        
        UIImage * image = [self.picMutableArray objectAtIndex:i];
        imageView.image = image;
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(didUserTappedImage:)];
        
        imageView.userInteractionEnabled = YES;
        
        [imageView addGestureRecognizer:tap];
        
        [scrollEffect addSubview:imageView];
    }
}

#pragma mark - FWEditGoodsTagViewDelegate (编辑商品标签)
// 点击取消按钮
- (void)editGoodsTagView:(FWEditGoodsTagView *)editGoodsTagView didClickCancelButtonWithModel:(Model *)model {
    
    self.goodsTagView.userInteractionEnabled = YES;
    [self.view bringSubviewToFront:self.goodsTagView];
    
}

// 点击完成按钮
- (void)editGoodsTagView:(FWEditGoodsTagView *)editGoodsTagView didClickFinishButtonWithModel:(Model *)model type:(FWEditGoodsTagViewType)type {

    self.goodsTagView.userInteractionEnabled = YES;
    if (type == FWEditGoodsTagViewTypeAdd) {
        // 添加新标签
        FWGoodsTagView *goodsTagView = [[FWGoodsTagView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width * 2, 100)];
        goodsTagView.center = self.goodsTagPoint;
        goodsTagView.delegate = self;
        [goodsTagView reloadWithModel:model];
        goodsTagView.backgroundColor = [UIColor clearColor];
        [self.tagLayerView addSubview:goodsTagView];
    } else if (type == FWEditGoodsTagViewTypeModify) {
        [self.goodsTagView reloadWithModel:model];
    }
}

// 点击删除按钮
- (void)editGoodsTagView:(FWEditGoodsTagView *)editGoodsTagView didClickDeleteButtonWithModel:(Model *)model {
    [self.goodsTagView removeFromSuperview];
}

#pragma mark - FWGoodsTagViewDelegate (商品标签)
- (void)goodsTagView:(FWGoodsTagView *)goodsTagView tapWithModel:(Model *)model {
    self.goodsTagView = goodsTagView;
    
    if (_editGoodsTagView) {
        [_editGoodsTagView removeFromSuperview];
        _editGoodsTagView = nil;
    }
    
    _editGoodsTagView = [[FWEditGoodsTagView alloc] initWithFrame:self.view.bounds];
    _editGoodsTagView.delegate = self;
    _editGoodsTagView.type = FWEditGoodsTagViewTypeModify;
    [_editGoodsTagView reloadEditGoodsTagViewWithModel:model];
    [self.view addSubview:_editGoodsTagView];

}


@end
